// import 'dart:developer';

import 'package:flutter/material.dart';
import './service/service_method.dart';
import 'dart:convert'; // 解析json
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:provide/provide.dart';
import './provide/child_category_provide.dart';
import './model/category.dart';
import './model/categoryGoodsListModel.dart';
import './provide/category_goods_list_provide.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:fluro/fluro.dart';
// import './routers/routers_handler.dart';


class CategoryPage extends StatelessWidget {
  
  const CategoryPage({Key key}) : super(key: key);
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('商品分类',)
      ),
        body: Container(
          child: Row(
            children: <Widget>[
              LeftCategoryNav(),
              Column(
                children: <Widget>[
                  RightCategoryNav(),
                  GetGoodsListSate()
                ],
              )
            ],
          ),
      )
    );
  }
}

class LeftCategoryNav extends StatefulWidget {
  LeftCategoryNav({Key key}) : super(key: key);

  _LeftCategoryNavState createState() => _LeftCategoryNavState();
}

class _LeftCategoryNavState extends State<LeftCategoryNav> {
  List list = [];
  var listIndex = 0;
  @override
  void initState() {
    _getCategory();
    _getGoodList('4');
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      width: ScreenUtil().setWidth(180),
      decoration: BoxDecoration(
          border: Border(
            right: BorderSide(
            width: 1.0,
            color: Colors.black12,
          )
        )
      ),
      child: ListView.builder(
        itemBuilder: (context,index){
          return _leftInkwell(index);
        },
        itemCount: list.length,
      ),
    );
  }

  Widget _leftInkwell(int index) {
    bool isClick = false;
    isClick = (index == listIndex) ? true : false;

    return InkWell(
      onTap: () {
        setState(() {
          listIndex = index; 
        });
        List childList = list[index].bxMallSubDto;
        String categoryId = list[index].mallCategoryId;
        Provide.value<ChildCategory>(context).getChildCategory(childList,categoryId);
        // 大类Id
        Provide.value<ChildCategory>(context).changeCategoryId(categoryId);
        // 二级分类索引为0
        Provide.value<ChildCategory>(context).changeChildIndex(0);
        _getGoodList(categoryId);
      },
      child: Container(
        height: ScreenUtil().setHeight(100),
        padding: EdgeInsets.only(top: 10.0, bottom: 10.0),
        alignment: Alignment.center,
        decoration: BoxDecoration(
            color: isClick ? Colors.black12 : Colors.white,
            border: Border(
              bottom: BorderSide(
                width: 1.0,
                color: Colors.black12
              )
              )
            ),
            child: Text(
              list[index].mallCategoryName,
              style: TextStyle(
                fontSize: ScreenUtil().setSp(28)
              ),
            ),
      ),
    );
  }

  void _getCategory() async {
    request('getCategory').then((val) {
      var data = json.decode(val.toString());
      CategoryModel categoryList = CategoryModel.fromJson(data);
      setState(() {
        list = categoryList.data;
      });
      // 初始化tab
      Provide.value<ChildCategory>(context).getChildCategory(list[0].bxMallSubDto,list[0].mallCategoryId);
    });
  }

  
void _getGoodList(String categoryId)async {
  var data={
      'categoryId':categoryId,
      'categorySubId':"",
      'page':1
    };
    await request('getMallGoods',formData:data ).then((val){
        var  data = json.decode(val.toString());
        CategoryGoodsListModel goodsList =  CategoryGoodsListModel.fromJson(data);
        // 修改列表状态
        Provide.value<CategoryGoodsListProvied>(context).getGoodsList(goodsList.data);
        // setState(() {
        // list= goodsList.data;
        // });
    });
  }
}

// 右侧二级导航
class RightCategoryNav extends StatefulWidget {
  RightCategoryNav({Key key}) : super(key: key);

  _RightCategoryNavState createState() => _RightCategoryNavState();
}
// 右侧二级导航
class _RightCategoryNavState extends State<RightCategoryNav> {

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Provide<ChildCategory>(
    builder:(context,child,childCategory){
      return Container(
        height: ScreenUtil().setHeight(80.0),
        width: ScreenUtil().setWidth(570.0),
        decoration: BoxDecoration(
          color:Colors.white,
          border: Border(
            bottom:BorderSide(width:1.0,color: Colors.black12)
          )
        ),
        child: ListView.builder(
          // 方向
          scrollDirection: Axis.horizontal,
          itemCount: childCategory.childCategoryList.length,
          itemBuilder: (context,index){
            return _rightInkell(childCategory.childCategoryList[index],index);
          },
        ),
      );
      }
    );
  }

  // 二级分类点击事件
  Widget _rightInkell( BxMallSubDto item,int index){
    
    bool isClick = false;
    int childIndex = Provide.value<ChildCategory>(context).childIndex;
    String categoryId = Provide.value<ChildCategory>(context).categoryId;
    String mallSubId = item.mallSubId;
    isClick = (childIndex == index) ? true:false;
    return InkWell(
      onTap: (){
        Provide.value<ChildCategory>(context).changeChildIndex(index);
        // 设则二级分类ID
        Provide.value<ChildCategory>(context).changCategorySubId(mallSubId);
        _getGoodList(categoryId,mallSubId);
      },
      child: Container(
        padding: EdgeInsets.fromLTRB(5.0,10.0,5.0,10.0),
        child: Text(
          item.mallSubName,
          style: TextStyle(
            fontSize: ScreenUtil().setSp(28),
            color:isClick?Colors.pink:Colors.black
          ),
        ),
      ),
    );
  }
  void _getGoodList(String categoryId,String mallSubId)async {
  var data={
      'categoryId':categoryId,
      'categorySubId':mallSubId,
      'page':1
    };
    await request('getMallGoods',formData:data ).then((val){
        var  data = json.decode(val.toString());
        CategoryGoodsListModel goodsList =  CategoryGoodsListModel.fromJson(data);
        // 修改列表状态
        if(goodsList.data==null){
          Provide.value<CategoryGoodsListProvied>(context).getGoodsList([]);
        }else{
          Provide.value<CategoryGoodsListProvied>(context).getGoodsList(goodsList.data);
        }
        // setState(() {
        // list= goodsList.data;
        // });
    });
  }
}


// 商品列表 上拉加载
class GetGoodsListSate extends StatefulWidget {
  GetGoodsListSate({Key key}) : super(key: key);

  _GetGoodsListSateState createState() => _GetGoodsListSateState();
}

class _GetGoodsListSateState extends State<GetGoodsListSate> {
  GlobalKey<RefreshFooterState> _footerkey = new GlobalKey<RefreshFooterState>();
   void _getMoreList()async {
     Provide.value<ChildCategory>(context).addPage();
      var data={
          'categoryId':Provide.value<ChildCategory>(context).categoryId,
          'categorySubId':Provide.value<ChildCategory>(context).categorySubId,
          'page':Provide.value<ChildCategory>(context).page,
        };
      await request('getMallGoods',formData:data ).then((val){
          var  data = json.decode(val.toString());
          CategoryGoodsListModel goodsList =  CategoryGoodsListModel.fromJson(data);
          if(goodsList.data==null){
            Provide.value<ChildCategory>(context).changeNoMore('没有更多商品...');
              // https://pub.dev/packages/fluttertoast   pub地址
              Fluttertoast.showToast(
                msg: "已经到底....",
                // 插件 shot // long
                toastLength: Toast.LENGTH_SHORT,
                // 提示位置 上 中 下
                gravity: ToastGravity.CENTER,
                timeInSecForIos: 1,
                // 背景色
                backgroundColor: Colors.pink,
                // 文字颜色
                textColor: Colors.white,
                // 文字大小
                fontSize: 16.0
            );
          }else{
            // 修改列表状态
            Provide.value<CategoryGoodsListProvied>(context).getMoreGoodsList(goodsList.data);
          }
      });
    }


  @override
  Widget build(BuildContext context) {
    return Provide<CategoryGoodsListProvied>(
      builder:(context,child,data){
        if(data.goodsList.length>0){
          return Container(
            width: ScreenUtil().setWidth(560),
            height: ScreenUtil().setHeight(970), 
            child:EasyRefresh(
              refreshFooter: ClassicsFooter(
                  key:_footerkey,
                  bgColor: Colors.white,
                  textColor: Colors.pink,
                  moreInfoColor:Colors.pink,
                  showMore: true,
                  noMoreText: Provide.value<ChildCategory>(context).noMoreText,
                  moreInfo: '加载中.....',
                  loadedText: '上拉加载',
                ),
                child:ListView.builder(
                  itemCount: data.goodsList.length,
                  itemBuilder: (context, index){
                    return _listWidgetItem(data.goodsList,index);},
                ),
                loadMore: ()async{
                  _getMoreList();
                  print('加载更多.....');
                },
            )
          );
        }else{
          return Expanded(
            child: Center( 
              child: Text('此分类暂无商品'),
            ),
          );
        }
      } ,
    ); 
  }

  

  Widget _goodsImg(List newList,index){
    return Container(
      height: ScreenUtil().setWidth(180.0),
      child: Image.network(newList[index].image),
    );
  }

  Widget _goodsName(List newList,index){
    return Container(
      padding: EdgeInsets.all(5.0),
      width: ScreenUtil().setWidth(370.0),
      child: Text(
        newList[index].goodsName,
        maxLines: 2,
        overflow: TextOverflow.ellipsis,
        style: TextStyle(
          fontSize: ScreenUtil().setSp(28)
        ),
      ),
    );
  }

  Widget _goodsPrice(List newList,index){
    return Container(
      margin: EdgeInsets.only(top:20.0),
      width: ScreenUtil().setWidth(370),
      child: Row(
        children: <Widget>[
          Text('价格：￥${newList[index].presentPrice}'),
          Text('￥${newList[index].oriPrice}',
          style: TextStyle(
            fontSize:ScreenUtil().setSp(28),
            decoration: TextDecoration.lineThrough
            ),
          ),
        ], 
      ),
    );
  }

  Widget _listWidgetItem(List newList,index){
    return InkWell(
      onTap: (){
        Handler();
      },
      child: Container(
        padding: EdgeInsets.fromLTRB(0, 5.0, 0, 5.0),
        decoration: BoxDecoration(
          color: Colors.white,
          border: Border(
            bottom: BorderSide(width:1.0,color: Colors.black12)
          )
        ),
        child: Row(
          children: <Widget>[
            _goodsImg(newList,index),
            Column(
              children: <Widget>[
                _goodsName(newList,index),
                _goodsPrice(newList,index),
              ],
            )
          ],
        ),
      ),
    );
  }
}